package com.mc.lp.core.util;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;

import org.springframework.util.CollectionUtils;

/**
 * collection util for utility functions
 * 
 * @author deepak
 * 
 */
public class CollectionUtil {
	// will use later to write common collection method, like paging and all

	public static Integer[] convertStringArraytoIntArray(String[] sarray) throws Exception {
		if (sarray != null) {
			Integer intarray[] = new Integer[sarray.length];
			for (int i = 0; i < sarray.length; i++) {
				intarray[i] = Integer.parseInt(sarray[i]);
			}
			return intarray;
		}
		return null;
	}

	public static Long[] convertStringArraytoLongArray(String[] sarray) throws Exception {
		if (sarray != null) {
			Long longArray[] = new Long[sarray.length];
			for (int i = 0; i < sarray.length; i++) {
				longArray[i] = Long.parseLong(sarray[i]);
			}
			return longArray;
		}
		return null;
	}

	public static String[] convertLongArraytoStringArray(Long[] larray) throws Exception {
		if (larray != null) {
			String stringArray[] = new String[larray.length];
			for (int i = 0; i < larray.length; i++) {
				stringArray[i] = String.valueOf(larray[i]);
			}
			return stringArray;
		}
		return null;
	}

	public static String[] sortStringArrayNumerically(String[] arr, SortOrder order) {

		final SortOrder sortOrder = order;

		try {

			Arrays.sort(arr, new Comparator<String>() {
				@Override
				public int compare(String o1, String o2) {

					if (sortOrder == SortOrder.ASCENDING)
						return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
					else
						return Integer.valueOf(o2).compareTo(Integer.valueOf(o1));

				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}
		return arr;

	}

	public static <O> O getObject(Set<O> list, O object) {
		if (CollectionUtils.isEmpty(list)) {
			return null;
		} else {
			if (list.contains(object)) {
				Iterator<O> iterator = list.iterator();
				while (iterator.hasNext()) {
					O nextElement = iterator.next();
					if (nextElement != null && nextElement.equals(object)) {
						return nextElement;
					}
				}
			} else {
				return null;
			}
		}
		return null;
	}
	
	
}
